package cn.migu.music.hangupsms.common.config;

import cn.migu.music.common.httpclient.interceptor.FeignInterceptor;
import cn.migu.music.hangupsms.model.CLSmsSendReq;
import cn.migu.music.hangupsms.utils.chuanglan.SignatureUtils;
import com.alibaba.fastjson.JSON;
import feign.RequestTemplate;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.TreeMap;
import java.util.UUID;

/**
 * 创蓝短信平台签名
 *
 * @version 1.0 created by litao on 2023年08月8日 上午11:41:07
 */
@Service
public class CLSmsAuthInterceptor implements FeignInterceptor {
    @Autowired
    private HangUpSmsConfig hangUpSmsConfig;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        Collection<String> headerRemote = requestTemplate.headers().get("remote");
        if (CollectionUtils.isNotEmpty(headerRemote) &&
            (headerRemote.contains("cl-sms-service"))) {
            long now = System.currentTimeMillis();
            String nonce = UUID.randomUUID().toString();
            String timestamp = String.valueOf(now);

            // 组装请求体 json
            String reqStr = getReqStr(requestTemplate);
            // 重新将请求参数body规范化，使用JSON序列化的json串
            requestTemplate.body(reqStr);
            // sign
            String signature = signature(hangUpSmsConfig.getClSmsSetting().getAppKey(), nonce, timestamp, reqStr,
                hangUpSmsConfig.getClSmsSetting().getAppSecret());

            setHeader(requestTemplate, signature, nonce, timestamp);
        }
    }

    private String getReqStr(RequestTemplate requestTemplate) {
        // 创蓝短信请求参数
        String body = new String(requestTemplate.body());
        CLSmsSendReq clSmsSendReq = JSON.parseObject(body, CLSmsSendReq.class);
        return JSON.toJSONString(clSmsSendReq);
    }

    private void setHeader(RequestTemplate requestTemplate, String signature, String nonce, String timestamp) {
        requestTemplate.header("Content-Type", "application/json; charset=UTF-8");
        requestTemplate.header("Charset", "UTF-8");
        requestTemplate.header("x-appkey", hangUpSmsConfig.getClSmsSetting().getAppKey());
        requestTemplate.header("x-nonce", nonce);
        requestTemplate.header("x-timestamp", timestamp);
        requestTemplate.header("x-signature", signature);
    }

    private String signature(String appKey, String nonce, String now, String reqStr, String appSecret) {
        TreeMap<String, String> paramMap = new TreeMap<>();
        paramMap.put(SignatureUtils.APP_KEY, appKey);
        paramMap.put(SignatureUtils.NONCE, nonce);
        paramMap.put(SignatureUtils.TIMESTAMP, now);
        paramMap.put("body", reqStr);
        return SignatureUtils.sign(appSecret, paramMap);
    }
}
